//获取滚动区域对象
let slideWrap = document.getElementById('slide-wrap');
//获取滚动对象
let slideContent = slideWrap.getElementsByClassName('slide-content')[0];
//获取图片对象
let liItem = slideContent.getElementsByTagName('li');
//获取可视区域宽度
let viewWidth = document.documentElement.clientWidth || document.body.clientWidth;
//获取分页的按钮对象
aItem = slideWrap.getElementsByClassName('slide-nav')[0].getElementsByTagName('a');
//获取next按钮对象
let nextButton = slideWrap.getElementsByClassName('slide-next')[0];
//获取prev对象
let prevButton = slideWrap.getElementsByClassName('slide-prev')[0];
//记录当前图片索引位置
let currentIndex = 0;
//滚动开关
let flag = false;
//计时器
flagTimer = null;
//自动播放计时器
autoTimer = null;

// 设置轮播区域宽度
slideContent.style.width = viewWidth * liItem.length + 'px';
//设置li图片宽度
for (let i = 0; i < liItem.length; i++) {
  liItem[i].style.width = viewWidth + 'px';
}
//分页按钮点击事件
for (let i = 0; i < aItem.length; i++) {
  aItem[i].onclick = function () {
    currentIndex = i;
    slide(i);
  }
}

autoPlay();

//鼠标事件
slideWrap.onmouseenter = function () {
  clearInterval(autoTimer);
}
slideWrap.onmouseleave = function () {
  autoPlay();
}
//自动滚动
function autoPlay() {
  autoTimer = setInterval(() => {
    next();
  }, 3000);
}
//滚动
function slide(number) {
  let left = number * viewWidth;
  slideContent.style.left = -left + 'px';
  flagTimer = setTimeout(() => {
    flag = false;
    clearTimeout(flagTimer);
  }, 1000);
  highLight();
}

// next按钮点击事件
nextButton.onclick = function () {
  if (flag) {
    return false;
  }
  flag = true;
  next();
}

function next() {
  currentIndex++;
  if (currentIndex == aItem.length) {
    currentIndex = 0;
  }
  slide(currentIndex);
}
//prev按钮点击事件
prevButton.onclick = function () {
  if (flag) {
    return false;
  }
  flag = true;
  prev();
}

function prev() {
  currentIndex--;
  if (currentIndex < 0) {
    currentIndex = aItem.length - 1;
  }
  slide(currentIndex);
}
//高光
function highLight() {
  for (let i = 0; i < liItem.length; i++) {
    aItem[i].className = '';
  }
  aItem[currentIndex].className = 'current';

}